package util
{
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.display.Stage;
	import flash.events.MouseEvent;
	import flash.geom.Rectangle;
	import flash.utils.Dictionary;
	
	import mx.managers.DragManager;
	
	import util.err.SingletonInstantiationErr;
	import util.err.StageNoSetErr;

	/**
	 * 拖动用的管理类 
	 * @author ZhongZw
	 * 
	 */	
	public class DragHelper
	{
		private static var _instance:DragHelper;
		
		private var _dragObjects:Object; 
		
		private var _curDragObject:Sprite;
		
		private var _stage:Stage;
		
		public function DragHelper()
		{
			if( _instance ) throw new SingletonInstantiationErr();
			
			_dragObjects = [];
		}
		
		public function init( stage:Stage ):void
		{
			this._stage = stage;
		}
		
		public function registDrag( dragObject:Sprite, x:Number = 0, y:Number = 0, width:Number = -1, height:Number = -1, lockCenter:Boolean = false ):void
		{
			if( !_stage ) throw new StageNoSetErr();
			
			if( width < 0 )
			{
				width = _stage.stageWidth - dragObject.width;
			}
			
			if( height < 0 )
			{
				height = _stage.stageHeight - dragObject.height;	
			}
			
			_dragObjects[dragObject] = {};
			
			_dragObjects[dragObject].rect = new Rectangle( x, y, width, height );
			
			_dragObjects[dragObject].lockCenter = lockCenter; 
			
			dragObject.addEventListener( MouseEvent.MOUSE_DOWN,  mouseHandler );
			
		}
		
		public function unRegisterDrag( dragObject:Sprite ):void
		{
			dragObject.removeEventListener( MouseEvent.MOUSE_DOWN, mouseHandler );
			
			delete _dragObjects[dragObject];
		}
		
		
		private function mouseHandler( e:MouseEvent ):void
		{
			if( e.type == MouseEvent.MOUSE_DOWN )
			{
				_curDragObject = e.currentTarget as Sprite;
				
				var rect:Rectangle = _dragObjects[_curDragObject].rect;
				
				var _lockCenter:Boolean = _dragObjects[_curDragObject].lockCenter;
				
				_curDragObject.startDrag( _lockCenter, rect );
				
				_stage.addEventListener( MouseEvent.MOUSE_UP, mouseHandler );
			
			}
			else if( e.type == MouseEvent.MOUSE_UP )
			{
				if( _curDragObject )
				{
					_curDragObject.stopDrag();
					
					_curDragObject = null;
				}
				
				_stage.removeEventListener( MouseEvent.MOUSE_UP, mouseHandler );
			}
		}
		
		public static function instance():util.DragHelper
		{
			if( !_instance ) _instance = new util.DragHelper;
			
			return _instance;
		}
	}
}